const axios = require("axios");
const fs = require("fs");
const { createCanvas, loadImage } = require("canvas");
const rds = require("./rds");

// API 调用函数，返回请求结果
async function callAPI(uid) {
    const apiUrl = `https://mall.totembio.cn/api/get_mall_materials?cid=${uid}&qrt=mp_qr_only`;
    try {
        const response = await axios.get(apiUrl);
        return response.data;
    } catch (error) {
        console.error("API 调用失败:", error.message);
        return null;
    }
}

// 生成二维码图片函数
async function generateQRCode(uid, qrCodeUrl) {
    // 获取 QR Code 图像的宽度和高度
    let qrCodeWidth, qrCodeHeight;
    try {
        const response = await axios.head(qrCodeUrl);
        qrCodeWidth = 430; //Number(response.headers['content-length']) || 0 //返回值是54不怎么靠谱;
        qrCodeHeight = qrCodeWidth;
    } catch (error) {
        console.error("获取 QR Code 图像大小出错:", error.message);
        return null;
    }

    // 计算 Canvas 的宽度和高度，增加 120%
    const canvasWidth = Math.ceil(qrCodeWidth);
    const canvasHeight = Math.ceil(qrCodeHeight + 16);

    const canvas = createCanvas(canvasWidth, canvasHeight);
    const ctx = canvas.getContext("2d");

    try {
        const response = await axios.get(qrCodeUrl, {
            responseType: "arraybuffer",
        });
        const imageBuffer = Buffer.from(response.data);

        // 判断图片格式
        let imageType;
        const firstByte = imageBuffer[0];
        if (firstByte === 0xff && imageBuffer[1] === 0xd8) {
            imageType = "image/jpeg";
        } else if (firstByte === 0x89 && imageBuffer[1] === 0x50) {
            imageType = "image/png";
        } else {
            throw new Error("Unsupported image format");
        }

        const qrCodeImage = await loadImage(imageBuffer, imageType);

        // 设置 Canvas 的宽度和高度
        canvas.width = canvasWidth;
        canvas.height = canvasHeight;

        // 绘制白色背景
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, canvasWidth, canvasHeight);

        // 绘制 QR Code 图像
        ctx.drawImage(qrCodeImage, 0, 0, qrCodeWidth, qrCodeHeight);

        // 计算文字的宽度和高度
        const text = `MTA MP-AUTH-${uid}`;
        const textMetrics = ctx.measureText(text);
        const textWidth = textMetrics.width;
        const textHeight =
            textMetrics.actualBoundingBoxAscent +
            textMetrics.actualBoundingBoxDescent;

        // 计算文字的水平和垂直位置
        const textX = (canvasWidth - textWidth) / 2;
        const textY = canvasHeight - textHeight / 2;

        // 添加文字
        ctx.fillStyle = "#000000";
        ctx.font = "12px Arial";
        ctx.fillText(`MP-AUTH-${uid}`, textX, textY);

        // 保存图片
        const imageName = `MP-AUTH-${uid}.png`;
        const imagePath = `./public/${imageName}`;

        const out = fs.createWriteStream(imagePath);
        const stream = canvas.createPNGStream();

        return new Promise((resolve, reject) => {
            stream.pipe(out);
            out.on("finish", () => resolve(imageName));
            out.on("error", reject);
        });
    } catch (error) {
        console.error("生成二维码图片出错:", error.message);
        return null;
    }
}

// 主要处理逻辑
async function processRecords() {
    const query =
        "SELECT uid FROM tutem_mall.eb_user WHERE promoter_type = 4 AND title = 'MP-AUTH'";
    try {
        const connection = await rds.pool.getConnection();
        const [rows] = await connection.query(query);
        connection.release();

        for (const { uid } of rows) {
            const apiResponse = await callAPI(uid);

            if (apiResponse) {
                const qrCodeUrl = apiResponse;
                const imageName = await generateQRCode(uid, qrCodeUrl);
                console.log(
                    "insert authentication mpcode as mageName:",
                    imageName
                );

                // 插入新纪录到数据库
                const insertQuery =
                    "INSERT INTO tutem_mall.mp_authentication (channel_id, qr_code_url) VALUES (?, ?)";
                const values = [
                    uid,
                    `https://totemlife.cn/apps/public/${imageName}`,
                ];
                const connection2 = await rds.pool.getConnection();
                await connection2.query(insertQuery, values);
                connection2.release();
            }
        }
    } catch (error) {
        console.error("数据库查询或插入出错:", error.message);
    }
}

//processRecords();
